package com.springboot2.controller;

import com.springboot2.entity.Cars;
import com.springboot2.service.CarsService;
import com.springboot2.utils.Result;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("cars/")
public class CarsController {

    @Resource
    private CarsService carsService;
    //增
    @PostMapping("add/{userId}/{goodsId}")
    public Result add(@RequestBody Cars cars,@PathVariable int userId,@PathVariable int goodsId){
        carsService.add(cars,userId,goodsId);
        return Result.success();
    }
    //删
    @DeleteMapping("del/{id}")
    public Result del(@PathVariable int id){
        carsService.del(id);
        return Result.success();
    }
    //改
    @PutMapping("update")
    public Result update(@RequestBody Cars cars){
        carsService.update(cars);
        return Result.success();
    }
    //获取对象
    @GetMapping("findById/{id}")
    public Result findById(@PathVariable int id){
        return Result.success(carsService.findById(id));
    }
    //分页列表
    @GetMapping("findByPage/{pageNo}/{pageSize}")
    public Result findByPage(@PathVariable int pageNo,@PathVariable int pageSize){
        Map<String ,Object> map = new HashMap<>();
        map.put("data",carsService.findByPage(pageNo, pageSize));
        map.put("total",carsService.count());
        return Result.success(map);
    }
    //查询所有的数据
    @GetMapping("findAll/{userId}")
    public Result findAll(@PathVariable int userId){
        return Result.success(carsService.findAll(userId));
    }
    //批量删除
    @DeleteMapping("batch/{ids}")
    @Transactional
    public Result batch(@PathVariable String ids){
        String [] splits = ids.split(",");
        for(String s:splits){
            carsService.del(Integer.parseInt(s));
        }
        return Result.success();
    }
}
